/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode *dummyNode = new ListNode(-1);
        dummyNode->next = head;
        ListNode *pre = dummyNode;
        ListNode *start = dummyNode;
        for (int i = 0; i < left - 1; i++) {
            pre = pre->next;
            start = start->next;
        }
        pre = pre->next;
        ListNode* end = pre;
        ListNode* cur = pre->next;
        for (int i = 0; i < right - left; i++) {
            ListNode *tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        } 
        start->next = pre;
        end->next = cur;
        return dummyNode->next;
    }
};


// 法二：
// 在需要反转的区间里，每遍历到一个节点，让这个新节点来到反转部分的起始位置。
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* pre = dummy;
        for (int i = 0; i < left - 1; ++i) {
            pre = pre->next;
        }
        ListNode* cur = pre->next;
        for (int i = left; i < right; ++i) {
            ListNode* next = cur->next;
            cur->next = next->next;
            next->next = pre->next;
            pre->next = next;
        }
        return dummy->next;
    }
};